package com.user.query.utils;

import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.*;

public class BGTutils {
    /**
     * 读取excel
     */
    public static void getExcelFile(String filepath) throws IOException {
        InputStream is=new FileInputStream(filepath);
        POIFSFileSystem fs=new POIFSFileSystem(is);
        HSSFWorkbook wb=new HSSFWorkbook(fs);
        ExcelExtractor et=new ExcelExtractor(wb);
        et.setIncludeSheetNames(false);
        System.out.println(et.getText());
    }
    /**
     * dir目录循环
     * @param dir
     */
    public static void getExcelFromDir(String dir) throws IOException {
         File file=new File(dir);
        if (file.isDirectory()) {
            // 目标文件
            FileOutputStream fOut = null;
            // 创建Excel的工作书册 Workbook,对应到一个excel文档
            Workbook wb = new HSSFWorkbook();
            // 创建Excel的工作sheet,对应到一个excel文档的tab
            Sheet sheet = wb.createSheet("sheet1");
            sheet.setColumnWidth(1,50*256);//对第二列设置宽度
            Row row=sheet.createRow(0);
            row.createCell(0).setCellValue("序号");
            row.createCell(1).setCellValue("文件名");
            row.createCell(2).setCellValue("大小");
            File[] files=file.listFiles();
            int len=files.length;
            for (int i=0;i<len;i++) {
                File fftem=files[i];
                Row rowtem=sheet.createRow(i+1);
                rowtem.createCell(0).setCellValue(i+1);
                rowtem.createCell(1).setCellValue(fftem.getName());
                rowtem.createCell(2).setCellValue(fftem.length()/(1024*1024)+"MB");
            }
            // 新建一输出文件流
            fOut = new FileOutputStream(new File("e:\\群文件目录.xls"));
            // 把相应的Excel 工作簿存盘
            wb.write(fOut);
            fOut.flush();
            // 操作结束，关闭文件
            fOut.close();

        }
    }

    public static void main(String[] args) throws Exception {
       BGTutils.getExcelFromDir("d:\\329019348");
       // File file=new File("d:\\329019348");
       // System.out.println(file.listFiles());
        BGTutils.getExcelFile("e:\\群文件目录.xls");
    }
}
